package com.xoa.util.sendUtil;




import com.xoa.service.smsDelivery.Sms2PrivService;
import com.xoa.service.smsDelivery.impl.Sms2PrivServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.*;
import java.util.Date;
import java.util.UUID;

@Component
public class send {

    @Autowired
    private Sms2PrivService sms2PrivService;

    private static send send;

    public void setSms2PrivService(Sms2PrivService sms2PrivService) {
        this.sms2PrivService = sms2PrivService;
    }

    @PostConstruct
    public void init() {
        send = this;
        send.sms2PrivService = this.sms2PrivService;

    }


    /**
     * 发送短信
     *
     * @param username	    用户名
     * @param pwd			密码
     * @param mobileString	电话号码字符串，中间用英文逗号间隔
     * @param contextString	内容字符串
     * @param sign			签名
     * @param time_content  追加发送时间，可为空，为空为及时发送
     * @param extend_2		扩展码，必须为数字 可为空
     * @return
     * @throws Exception
     */
    public static String doPost(StringBuffer mobileString, StringBuffer contextString,String protocol, String host,String port,
                                String username,String pwd,String content_field,
                                String code,String mobile,String time_content,String sign, String location,
                                String extend_1,String extend_2,String extend_3,String extend_4,String extend_5,String startTime
                                ) throws Exception {
        StringBuffer param = new StringBuffer();
        param.append(username);
        param.append("&"+pwd);
        param.append("&"+mobile+"=").append(mobileString);

        if(!"".equals(contextString)){
            if("1".equals(code)){
                if("0".equals(extend_5)){
                    param.append("&"+content_field+"="+contextString.toString());
                }else if("1".equals(extend_5)){
                    String[] sign1 = sign.split("=");
                    if("【徐州开发区教育局】".equals(sign1[1])) {
                        param.append("&"+content_field+"=").append(URLEncoder.encode(sign1[1] + contextString.toString(),"UTF-8"));
                    }else{
                        param.append("&"+content_field+"=").append(URLEncoder.encode(contextString.toString(),"UTF-8"));
                    }
                    // param.append("&"+content_field+"=").append("好不好");
                }

            }else if("0".equals(code)){
                if("0".equals(extend_5)){
                    param.append("&"+content_field+"=").append(contextString.toString());
                }if("1".equals(extend_5)){
                    param.append("&"+content_field+"=").append(URLEncoder.encode(contextString.toString(),"GBK"));
                }
            }
        }

        if(!"".equals(sign)){
            if("1".equals(code)){
                if("0".equals(extend_5)){
                    param.append("&"+sign);
                }else if("1".equals(extend_5)){
                    String[] sign1 = sign.split("=");
                    param.append("&"+sign1[0]+"="+(URLEncoder.encode(sign1[1],"UTF-8")));
                }
            }else if("0".equals(code)){
                if("0".equals(extend_5)){
                    param.append("&"+sign);
                }else if("1".equals(extend_5)){
                    param.append("&"+(URLEncoder.encode(sign,"GBK")));
                }
            }
        }
        if("1".equals(code)){
            code="utf-8";
        }else if("0".equals(code)){
            code="GBK";
        }
        if(startTime==null){
            startTime="";
        }
        if(!"".equals(time_content)&& time_content!=null){
            param.append("&"+time_content+"="+startTime);
        }



        if(!"".equals(extend_1)){
            param.append("&"+extend_1);
            //兼容定西巉口短信
            if(extend_1.equals("SpCode=203912")){
                param.append("&SerialNumber="+new Date().getTime());
            }
            //兼容牟平短信
            if(extend_1.equals("SpCode=240584")){
                param.append("&SerialNumber="+new Date().getTime());
            }
        }
        if(!"".equals(extend_2)){
            param.append("&"+extend_2);
        }
        if(!"".equals(extend_3)){
            param.append("&"+extend_3);
        }
        if(!"".equals(extend_4)){
            param.append("&"+extend_4);
        }



        URL localURL = new URL(protocol+"://"+host+"/"+port+"?");
        //在你发起Http请求之前设置一下属性
//        InetSocketAddress addr = new InetSocketAddress("127.0.0.1",8888);
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理

        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset",code);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String resultBuffer = "";

        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(param.toString());
            outputStreamWriter.flush();
            httpURLConnection.connect();
          if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseMessage());
            }

            inputStream = httpURLConnection.getInputStream();
            resultBuffer = convertStreamToString(inputStream);

        } finally {

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer;
    }


    /**
     * 转换返回值类型为UTF-8格式.
     * @param is
     * @return
     */
    public static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size = 0;

        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }


    /**
     *李阳
     * 2018.10.15
     * 恩施 短信
     * @param Phone   接短信手机号
     * @param ecpId  发短信手机号
     * @param message 短信内容
     * @param byName  验证发信人是否有发送权限
     * @param overName 验证收信人是否有收的权限
     * @throws ClientProtocolException
     * @throws IOException
     */
    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(5000).setConnectTimeout(3000).build();
    public static void sms(String Phone,String ecpId,String message,String byName,String overName) throws ClientProtocolException,
            IOException {



    }


}

